<template>
    <div class="wrapper">
        <div class="default-title" v-show="showTips">欢迎登陆ADS平台,为了不影响您正常投入广告,请先绑定您的平台账户</div>
        <div style="height: 25px" v-show="!showTips"></div>
        <div class="setting">
            <div class="item">
                <div class="item-count">
                    <div class="font-wrapper1">
                        <i class="iconfont icon-Facebook"></i>
                    </div>
                    <span>Facebook</span>
                </div>
                <div class="item-bind" v-show="!bindFB">
                    <span></span>
                    <el-button v-show="!bindStatus" class="yellow-button-small" @click="loginFB">授权</el-button>
                    <el-button v-show="bindStatus" class="yellow-button-small" :loading="true">授权中</el-button>
                </div>
                <div class="item-bind" v-show="bindFB">
                    <div class="btn_common_grey btn_common_small">已授权</div>
                    <span style="cursor:pointer;" @click="cancelBind(0)">取消授权</span>
                </div>
            </div>
            <div class="sub-item">
                <div class="header-img" v-show="bindFB">
                    <img v-if="showDefaultFBImg" src="../../assets/img/header/facebook.jpeg"/>
                    <img v-if="!showDefaultFBImg" :src="FBImg"/>
                </div>
                <div class="header-name" v-show="bindFB">{{FBName}}</div>
                <div class="header-name" v-show="bindFB">{{FBId}}</div>
            </div>

            <div class="item">
                <div class="item-count">
                    <div class="font-wrapper1">
                        <i class="iconfont icon-google"></i>
                    </div>
                    <span>Google</span>
                </div>
                <div class="item-bind" v-show="!bindGoogle">
                    <span></span>
                    <el-button v-show="!bindGoogleStatus" class="yellow-button-small" @click="loginGoogle">授权</el-button>
                    <el-button v-show="bindGoogleStatus" class="yellow-button-small" :loading="true">授权中</el-button>
                </div>
                <div class="item-bind" v-show="bindGoogle">
                    <div class="btn_common_grey btn_common_small">已授权</div>
                    <span style="cursor:pointer;" @click="cancelBind(1)">取消授权</span>
                </div>
            </div>
            <div class="sub-item">
                <div class="header-img" v-show="bindGoogle && chooseGoogleId">
                    <img v-if="showDefaultGoogleImg" src="../../assets/img/header/google.jpeg"/>
                    <img v-if="!showDefaultGoogleImg" :src="GoogleImg"/>
                </div>
                <div class="header-name" v-show="bindGoogle && chooseGoogleId">{{GoogleName}}</div>
                <div class="header-name" v-show="bindGoogle && chooseGoogleId">{{GoogleID}}</div>
            </div>
        </div>
        <div class="btn-create">
            <div class="btn_common_grey" v-show="!bindFB && !bindGoogle" style="cursor: not-allowed">创建广告</div>
            <nuxt-link to="/create">
                <div class="btn_common_yellow" v-show="bindFB || bindGoogle">创建广告</div>
            </nuxt-link>
        </div>

        <!--------选择Google账号弹出框---------->
        <el-dialog title="选择Google账号" v-model="showGoogleAccount" class="el-call" >
            <el-table :data="googleList" height="245">
                <el-table-column label="选择" width="80">
                    <template scope="scope" >
                        <el-radio-group v-model="chooseGoogle"  @change="handleGoogleAccount">
                            <el-radio class="radio" :label="scope.row.clientCustomerId" >
                                <span style="display: none">1</span>
                            </el-radio>
                        </el-radio-group>
                    </template>
                </el-table-column>
                <el-table-column property="name" label="账户名称" width="200"></el-table-column>
                <el-table-column property="clientCustomerId" label="账户ID"></el-table-column>
            </el-table>
            <div slot="footer">
                <div class="btn_common_white btn_common_small btn_common_cancel" @click="handleCancelAccount" >取消</div>
                <el-button v-if="!chooseAccount" class="yellow-button-small" @click="handleChooseAccount">确定</el-button>
                <el-button v-if="chooseAccount" class="yellow-button-small" :loading="true">授权中</el-button>
            </div>
        </el-dialog>

        <!--------创建Google账号弹出框---------->
        <el-dialog title="创建Google账号" v-model="showCreateGoogleAccount" class="el-call" >
            <span class="create-txt">您还没有AdWords账户，请先前往Google AdWords</span>
            <el-button class="yellow-button-small" @click="createGoogleAccount">创建账户</el-button>
            <div slot="footer">
                <div class="btn_common_white btn_common_small btn_common_cancel" @click="handleCancelAccountCreate">取消</div>
            </div>
        </el-dialog>

        <!--取消授权-->
        <el-dialog v-model="showTipPopover" class="el-delete">
            <div class="tip-wrapper">
                <div class="tip-left">
                    <i class="iconfont icon-tip icon-tip2"></i>
                </div>
                <div class="tip-right">
                    <span class="tip-title">提示</span>
                    <span class="tip-txt">此操作将取消 {{cancelType==0 ? 'Facebook' : 'Google'}} 授权, 是否继续?</span>
                </div>
            </div>

            <div slot="footer">
                <div class="btn_common_white btn_common_small btn_common_cancel" @click="showTipPopover = false">取消</div>
                <el-button v-if="!cancelStatus" class="yellow-button-small" @click="logout">确定</el-button>
                <el-button v-if="cancelStatus" class="yellow-button-small" :loading="true">取消授权中</el-button>
            </div>
        </el-dialog>
        <loading :customClass="customLoading" v-if="showLoading" />
    </div>
</template>
<script>
    import Vue from 'vue'
    import * as types from '../../store/mutation-types/account/index'
    import { setToken ,getParam, getCookie ,newWin ,loadDefaultImg} from '~/assets/js/global'
    import { basicConfig } from '~/assets/js/config'
    import { mapGetters} from 'vuex';
    import loading from '~/components/loading.vue'
    import { Message , Button ,Table , Radio , RadioGroup , Dialog ,TableColumn ,MessageBox} from 'element-ui'
    Vue.use(Button);
    Vue.use(Table);
    Vue.use(Radio);
    Vue.use(Dialog);
    Vue.use(TableColumn);
    Vue.use(RadioGroup);

    export default{
        head(){
            return{
                title: 'ADS-平台账户'
            }
        },
        components: {
            loading
        },
        data(){
            return{
                showLoading: false,
                customLoading : 'top:450px',
                showDefaultFBImg: true,
                showDefaultGoogleImg: true,
                showTips: false,
                showTipPopover: false,
                cancelType: '',
                chooseAccount: false,
                cancelStatus: false,
                chooseGoogle: '',
                googleList: [],
                showGoogleAccount: false,
                showCreateGoogleAccount: false,
                FBImg:'',
                FBName: '',
                FBId:'',
                GoogleImg:'',
                GoogleName: '',
                GoogleID: '',
                chooseGoogleId: false,
                formAccount: false
            }
        },
        updated() {
            if(!this.formAccount){
                if(!this.bindFB && !this.bindGoogle){
                    this.showTips = true;
                }
            }
        },
        methods: {
            //授权Facebook账号
            loginFB() {
                if(typeof FB == 'undefined'){
                    Message.warning({
                        message: '网络出问题或者您还没有打开翻墙软件.'
                    });
                    return false;
                }
                this.$store.commit(types.BIND_STATUS,{bindStatus: true});
                FB.login((response) => {
                    if (response.status === 'connected') {
                        //保存FB token
                        this.$store.dispatch('saveFBToken', {'fbToken':response.authResponse.accessToken})
                            .then((response) => {
                                if(response.data && response.data.code && (response.data.success)) {
                                    var result = response.data;
                                    setToken('FBInfo',result.data);
                                    this.FBImg= result.data.avatar;
                                    this.replaceDefaultImg(this.FBImg , 0);
                                    this.FBName = result.data.nickName;
                                    this.FBId = result.data.currentid;
                                    Message.success({
                                        message: 'Facebook账号授权成功'
                                    });
                                    this.showTips = false;
                                    this.$store.commit(types.BIND_FACEBOOK,{bindFacebook: true});
                                    this.$store.commit(types.BIND_STATUS,{bindStatus: false});
                                }else {
                                    this.$store.commit(types.BIND_FACEBOOK,{bindFacebook: false});
                                    this.$store.commit(types.BIND_STATUS,{bindStatus: false});
                                }
                            })
                            .catch((error) => {
                                this.$store.commit(types.BIND_FACEBOOK,{bindFacebook: false});
                                this.$store.commit(types.BIND_STATUS,{bindStatus: false});
                            });
                    }else{
                        Message.warning({
                            message: '您已取消授权Facebook账号'
                        });
                        this.$store.commit(types.BIND_FACEBOOK,{bindFacebook: false});
                        this.$store.commit(types.BIND_STATUS,{bindStatus: false});
                    }
                }, {
                    scope: 'email,ads_management,ads_read,manage_pages,pages_show_list',
                });
            },

            //退出Facebook账号
            logoutFB() {
                this.cancelStatus = true;
                this.$store.dispatch('unbindFB')
                    .then((response) => {
                        if(response.data && response.data.success) {
                            setToken('FBInfo',null);
                            Message.success({
                                message: 'Facebook账号解绑成功'
                            });
                            this.$store.commit(types.BIND_FACEBOOK,{bindFacebook: false});
                            this.cancelStatus = false;
                            this.showTipPopover = false;
                        }
                    })
            },
            cancelBind(type) {
                this.showTipPopover = true;
                this.cancelType = type
            },
            logout() {
                switch (this.cancelType) {
                    case 0:
                       this.logoutFB();
                       break;
                    case 1:
                        this.logoutGoogle();
                        break;
                }
            },

            //Google获取code
            loginGoogle() {
                this.$store.commit(types.BIND_GOOGLE_STATUS,{bindGoogleStatus: true});
                this.$store.dispatch('getGoogleCode')
                    .then((response) => {
                        if(response.data && response.data.success) {
                            window.location.href = response.data.data;
                        }else {
                            this.$store.commit(types.BIND_GOOGLE_STATUS,{bindGoogleStatus: false});
                        }
                    })
                    .catch((error) => {
                        this.$store.commit(types.BIND_GOOGLE_STATUS,{bindGoogleStatus: false});
                    });
            },

            //谷歌登录授权接口
            bindingGoogle(){    //拿到google的code之后授权
                this.$store.commit(types.BIND_GOOGLE_STATUS,{bindGoogleStatus: true});
                this.$store.dispatch('getAdwordsAccountsByCode',{'authorizationCode': getParam('code')})
                    .then((response) => {
                        if(response.data && response.data.success) {
                            let result = response.data.data;
                            if(result){
                                if(result.length > 1){
                                    this.showGoogleAccount = true;
                                    this.googleList = result;
                                    this.$store.commit(types.BIND_GOOGLE_STATUS,{bindGoogleStatus: false});
                                }
                                if(result.length == 1){
                                    setToken('GoogleInfo',result[0].clientCustomerId);
                                    this.GoogleID = result[0].clientCustomerId;
                                    this.chooseGoogleId = true;
                                    this.$store.commit(types.BIND_GOOGLE,{bindGoogle: true});
                                    this.$store.commit(types.BIND_GOOGLE_STATUS,{bindGoogleStatus: false});
                                }
                                if(result.length == 0){
                                    this.$store.commit(types.BIND_GOOGLE_STATUS,{bindGoogleStatus: false});
                                    this.showCreateGoogleAccount = true;
                                }
                            }
                        }else {
                            this.$store.commit(types.BIND_GOOGLE,{bindGoogle: false});
                            this.$store.commit(types.BIND_GOOGLE_STATUS,{bindGoogleStatus: false});
                        }
                    })
                    .catch((error) => {
                        this.$store.commit(types.BIND_GOOGLE,{bindGoogle: false});
                        this.$store.commit(types.BIND_GOOGLE_STATUS,{bindGoogleStatus: false});
                    });
            },

            //获取绑定信息列表
            getAllPlatformInfo() {
                this.showLoading = true;
                this.formAccount = true;
                this.$store.dispatch('getAllPlatformInfo')
                    .then((response) => {
                        var result = response.data;
                        if(result && result.success){
                            this.showLoading = false;
                            switch (result.data.length) {
                                case 0 :
                                    this.showTips = true;
                                    break;
                                case 1:
                                    if(result.data[0].platform == 1){
                                        setToken('FBInfo',result.data);
                                        setToken('GoogleInfo',null);
                                        this.FBImg= result.data[0].avatar;
                                        this.replaceDefaultImg(this.FBImg , 0);
                                        this.FBName = result.data[0].nickName;
                                        this.FBId = result.data[0].currentid;
                                        this.$store.commit(types.BIND_FACEBOOK,{bindFacebook: true});
                                        this.$store.commit(types.BIND_GOOGLE,{bindGoogle: false});
                                    }else if(result.data[0].platform == 2){
                                        setToken('FBInfo',null);
                                        setToken('GoogleInfo',result.data[0].currentid);
                                        this.GoogleImg= result.data[0].avatar;
                                        this.replaceDefaultImg(this.GoogleImg , 1);
                                        this.GoogleName = result.data[0].nickName;
                                        this.GoogleID = result.data[0].currentid;
                                        this.chooseGoogleId = true;
                                        this.$store.commit(types.BIND_FACEBOOK,{bindFacebook: false});
                                        this.$store.commit(types.BIND_GOOGLE,{bindGoogle: true});
                                    }
                                    break;
                                case 2:
                                    for(var i=0;i<result.data.length;i++){
                                        if(result.data[i].platform == 1){
                                            setToken('FBInfo',result.data);
                                            this.FBImg = result.data[i].avatar;
                                            this.replaceDefaultImg(this.FBImg , 0);
                                            this.FBName = result.data[i].nickName;
                                            this.FBId = result.data[i].currentid;
                                            this.$store.commit(types.BIND_FACEBOOK,{bindFacebook: true});
                                        }else if(result.data[i].platform == 2){
                                            setToken('GoogleInfo',result.data[i].currentid);
                                            this.GoogleImg= result.data[i].avatar;
                                            this.replaceDefaultImg(this.GoogleImg , 1);
                                            this.GoogleName = result.data[i].nickName;
                                            this.GoogleID = result.data[i].currentid;
                                            this.chooseGoogleId = true;
                                            this.$store.commit(types.BIND_GOOGLE,{bindGoogle: true});
                                        }
                                    }
                                    break;
                            }
                        }else {
                            this.showLoading = false;
                            this.showTips = true;
                            this.$store.commit(types.BIND_FACEBOOK,{bindFacebook: false});
                            this.$store.commit(types.BIND_GOOGLE,{bindGoogle: false});
                        }
                    })
                    .catch((error) => {
                        this.showLoading = false;
                        this.showTips = true;
                        this.$store.commit(types.BIND_FACEBOOK,{bindFacebook: false});
                        this.$store.commit(types.BIND_GOOGLE,{bindGoogle: false});
                    })
            },

            //退出Google账号
            logoutGoogle() {
                this.cancelStatus = true;
                this.$store.dispatch('unBindGoogle')
                    .then((response) => {
                        if(response.data && response.data.success) {
                            setToken('GoogleInfo',null);
                            Message.success({
                                message: 'Google账号解绑成功'
                            });
                            this.$store.commit(types.BIND_GOOGLE,{bindGoogle: false});
                            this.cancelStatus = false;
                            this.showTipPopover = false;
                        }
                    })
            },
            handleGoogleAccount(label) {
                this.chooseGoogle = label;
            },
            handleCancelAccount() {
                this.chooseGoogle = '';
                this.showGoogleAccount = false;
                setToken('GoogleInfo',null);
                this.$store.commit(types.BIND_GOOGLE,{bindGoogle: false});
            },
            handleCancelAccountCreate() {
                this.chooseGoogle = '';
                this.showCreateGoogleAccount = false;
                setToken('GoogleInfo',null);
                this.$store.commit(types.BIND_GOOGLE,{bindGoogle: false});
            },
            handleChooseAccount(){
                this.chooseAccount = true;
                this.$store.dispatch('settingGoogleAds',{'accountId': this.chooseGoogle})
                    .then((response) => {
                    let result = response.data;
                        if(result && result.success) {
                            this.chooseAccount = false;
                            this.showGoogleAccount = false;
                            this.GoogleImg= result.data.avatar;
                            this.replaceDefaultImg(this.GoogleImg , 1);
                            this.GoogleName = result.data.nickName;
                            this.GoogleID = result.data.currentid;
                            setToken('GoogleInfo',result.data.currentid);
                            this.chooseGoogleId = true;
                            this.$store.commit(types.BIND_GOOGLE,{bindGoogle: true});
                            Message.success({
                                message: 'Google账号授权成功'
                            });
                            this.showTips = false;
                        }else {
                            this.chooseAccount = false;
                            this.showGoogleAccount = false;
                            this.$store.commit(types.BIND_GOOGLE,{bindGoogle: false});
                        }
                    })
                    .catch((error) => {
                        this.chooseAccount = false;
                        this.showGoogleAccount = false;
                        this.$store.commit(types.BIND_GOOGLE,{bindGoogle: false});
                    });
            },
            createGoogleAccount() {
                this.showCreateGoogleAccount = false;
                newWin('https://adwords.google.com/home/#?modal_active=none','google');
            },
            replaceDefaultImg(img,type) {
                let that = this;
                let testImg = new Image();
                testImg.src = img;
                //如果目标图片加载成功，把默认图片替换成目标图片
                testImg.onload = function() {
                    if(type == 0){
                        that.showDefaultFBImg = false
                    }else {
                        that.showDefaultGoogleImg = false
                    }
                };
            }
        },
        computed: {
            ...mapGetters({
                'bindStatus': 'getBindStatus',
                'bindGoogleStatus': 'getBindGoogleStatus',
                'bindFB': 'getBindFacebook',
                'bindGoogle':'getBindGoogle',
                'feedbackStatus': 'getFeedbackStatus'
            })
        },
        watch: {
            bindFB: function () {
                if(!this.bindFB && !this.bindGoogle){
                    this.showTips = true;
                }
            },
            bindGoogle: function () {
                if(!this.bindFB && !this.bindGoogle){
                    this.showTips = true;
                }
            }
        },
        created(){
            if (process.BROWSER_BUILD ) {
                //根据页面code授权Google
                if(getParam('code')) {
                    this.bindingGoogle();    //根据谷歌授权码code获取token并绑定账号信息接口
                    let url = window.location.href.split('?')[0];
                    window.history.pushState({},0,url);
                }
            }
        },
        mounted() {
            this.getAllPlatformInfo();  //获取绑定信息列表
            window.fbAsyncInit = function() {
                FB.init({
                    appId      : basicConfig.appId,    //测试和香港服务器
                    status     : true,
                    xfbml      : true,
                    version    : 'v2.7',
                    cookie     : true
                });
            };
            (function(d, s, id){
                var js, fjs = d.getElementsByTagName(s)[0];
                if (d.getElementById(id)) {return;}
                js = d.createElement(s); js.id = id;
                js.src = "//connect.facebook.net/en_US/sdk.js";
                fjs.parentNode.insertBefore(js, fjs);
            }(document, 'script', 'facebook-jssdk'));
        }
    }
</script>

<style scoped lang="scss">
    .btn-disable {
        cursor: not-allowed !important;
    }
    .btn_common_cancel {
        margin-right: 20px;
    }
    .create-txt {
        font-size: 12px;
        color: #666;
        margin-right: 15px;
    }

    .wrapper{
        padding: 0 58px;
        background-color: #fff;
        min-height: 594px;
    .default-title {
        font-size: 14px;
        height: 50px;
        line-height: 50px;
        color: #666666;
        letter-spacing: 0;
        padding: 20px 0;
        text-align: center;
    }
    .setting {
        width: 100%;
        margin-bottom: 88px;
    .item {
        width: 580px;
        height: 60px;
        margin: 0 auto;
        background: #F4F7F9;
        border-radius: 4px;
        padding: 0 16px;
    .item-count {
        float: left;
    .font-wrapper1 {
        height: 60px;
        display: inline-block;
        float: left;
        width: 50px;
        text-align: center;
        line-height: 60px;
        .icon-Facebook {
            color: #43619C;
            font-size: 40px;
        }
        .icon-google {
            color: #101467;
            font-size: 40px;
        }
    }
    span {
        float: left;
        font-size: 16px;
        line-height: 60px;
        color: #333;
        margin-left: 15px;
    }
    }
    .item-bind {
        float: right;
    span {
        font-size: 13px;
        color: #0686F9;
        line-height: 60px;
        margin-left: 20px;
    }
    }
    }
    .sub-item {
        width: 500px;
        height: 55px;
        margin: 0 auto;
    .header-img {
        display: inline-block;
        float: left;
        margin: 10px 10px 0 0;
        width: 32px;
        height: 32px;
        border-radius: 16px;
        border: 1px solid #eee;
    img{
        border:none;
        outline:none;
        border-radius: 16px;
        width: 32px;
        height:32px;
    }
    }
    .header-name {
        font-size: 13px;
        color: #666666;
        letter-spacing: 0;
        line-height: 55px;
        float: left;
        margin-right: 10px;
    }
    }
    }
    .btn-create {
        text-align: center;
    }
    .btn_common_grey {
        cursor: default;
    }
    .btn_common_yellow{
        margin-left: 20px;
    }
    .tip-wrapper {
        display: inline-block;
        padding: 0 20px;
    .tip-left {
        color: #FFC000;
        font-size: 25px;
        float: left;
        text-align: center;
        line-height: 30px;
        margin-right: 15px;
    .icon-tip2 {
        font-size: 28px;
    }
    }
    .tip-right {
        float: left;
    .tip-title {
        float: left;
        width: 100%;
        font-size: 14px;
        color: #666666;
        line-height: 30px;
    }
    .tip-txt {
        float: left;
        font-size: 12px;
        color: #666666;
        line-height: 28px;
    }
    }
    }
    }
</style>